package com.bsoft.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
public class RedissonController {
    private static final String LOCK_KEY = "anylock";
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/redission")
    public void testRedission() throws InterruptedException {
        // 启动一个线程A 去占有锁
        new Thread(new Runnable() {
            @Override
            public void run() {
                //加锁以后10s自动解锁
                //无需调用unlock方法手动解锁
                final RLock lock = redissonClient.getLock(LOCK_KEY);
                lock.lock(10, TimeUnit.SECONDS);
            }
        }).start();
        // 简单sleep  1s  保证线程A成功持有锁
        Thread.sleep(1000L);
        //尝试加锁最多等待100s 上锁以后 10s 自动解锁
        System.out.println(String.format("准备开始获得锁时间：%s", new SimpleDateFormat("yyyy-MM-DD HH:mm:ss").format(new Date())));
        final RLock lock = redissonClient.getLock(LOCK_KEY);
        boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
        if (res) {
            System.out.println(String.format("实际获得锁时间：%s", new SimpleDateFormat("yyyy-MM-DD HH:mm:ss").format(new Date())));
        } else {
            System.out.println("加锁失败=========>");
        }
    }


}
